package com.gimi.cloud.bbp.common.utils;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Calendar;
import java.util.Date;

/**
 * 编码工具类
 * @author Administrator
 *
 */
public class SubTool {

	/** 设置编码格式 */
	public Charset charset = Charset.forName("UTF-8");
	/** 设置编码器 */
	public CharsetEncoder encoder = charset.newEncoder();
	/** 设置解码器 */
	public CharsetDecoder decoder = charset.newDecoder();

	/**
	 * 格式化String
	 * 
	 * @param bufferDate
	 * @param offset
	 * @param len
	 * @return
	 */
	public String formatString(byte[] bufferDate, int offset, int len) {
		ByteBuffer fromBuffer = ByteBuffer.wrap(bufferDate, offset, len);
		CharBuffer cfromBuf = CharBuffer.allocate(len);
		try {
			cfromBuf = decoder.decode(fromBuffer);
		} catch (CharacterCodingException e) {
			e.printStackTrace();
		}
		String strBuffer = new String(cfromBuf.array());
		return strBuffer.trim();
	}

	/**
	 * 格式化String
	 * 
	 * @param bufferDate
	 * @return
	 */
	public String formatString(byte[] bufferDate) {
		if (bufferDate == null)
			return null;
		ByteBuffer fromBuffer = ByteBuffer.wrap(bufferDate);
		CharBuffer cfromBuf = CharBuffer.allocate(bufferDate.length);
		try {
			cfromBuf = decoder.decode(fromBuffer);
		} catch (CharacterCodingException e) {
		}
		String strBuffer = new String(cfromBuf.array());
		return strBuffer.trim();
	}

	/**
	 * 格式化Date
	 * 
	 * @param buff
	 * @param offset
	 * @return
	 */
	public Date formatDate(ByteBuffer buff, int offset) {
		Calendar ca = Calendar.getInstance();
		ca.set((buff.getShort(offset)), buff.getShort(offset + 2) - 1, buff
				.getShort(offset + 6), buff.getShort(offset + 8), buff
				.getShort(offset + 10), buff.getShort(offset + 12));
		return ca.getTime();
	}

}
